using ConfigurationSettings;
using FileSystemControls;
using System;
using System.Windows.Forms;
using log4net;
using ServiceLocator;

namespace FileTracker
{

    public static class FileTrackerMain
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(FileTrackerMain));

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            using (ThreadContext.Stacks["NDC"].Push("MainEntryPoint"))
            {

				_log.DebugFormat("Register classes with Service Locator");
	            Locator.RegisterSingleton<IApplicationSettings,ApplicationSettings>();

				_log.DebugFormat("Set unhandled Exception handler");
                AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                _log.DebugFormat("Run the application");
                Application.Run(new MainApplicationContext());
            }
        }

        private static void AppDomainUnhandledException(object argSender, UnhandledExceptionEventArgs argEvtArgs)
        {
            Exception currentException;
            using (ThreadContext.Stacks["NDC"].Push("AppDomainUnhandledException"))
            {
                currentException = argEvtArgs.ExceptionObject as Exception;
                if (currentException == null)
                {
                    // this is an unmanaged currentException, you may want to handle it differently
                    _log.Fatal("Unmanaged Exception happened with no exception object attached. No telling what to do now.");
                    return;
                }

                _log.Info("Unhandled Exception caught in AppDomain handler.");
                _log.InfoFormat("Application is terminating: {0}", argEvtArgs.IsTerminating.ToString());
                _log.Info("Please see the following to determine cause", currentException);
            }
        }
    }
}